<template>
  <div class="publish-detail-container">
    <!-- AI 助手按钮 -->
    <el-button 
      type="primary" 
      icon="el-icon-robot" 
      @click="showAIAssistant"
      class="ai-assistant-btn"
    >
      AI 助手
    </el-button>
    <div class="header-section">
      <div class="header-content">
        <h2>{{ testInfo.purpose }}</h2>
        <div class="meta-info">
          <span class="meta-item"><i class="el-icon-user"></i> 学生: {{ studentName }}</span>
          <span class="meta-item"><i class="el-icon-timer"></i> 截止时间: {{ formatDate(testInfo.endTime) }}</span>
          <span class="meta-item"><i class="el-icon-trophy"></i> 总分: {{ studentTotalScore }}/{{ testInfo.totalScore }}分</span>
          <span class="meta-item"><i class="el-icon-tickets"></i> 题目数: {{ questionDetails.length }}</span>
          <el-tag v-if="isExpired" type="danger">已截止</el-tag>
          <el-tag v-else type="warning">未截止</el-tag>
        </div>
      </div>
      <div class="action-buttons">
        <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
        <el-button type="success" icon="el-icon-check" @click="saveGrades" :loading="saving" :disabled="!hasChanges">保存评分</el-button>
      </div>
    </div>
    
    <div class="questions-list" v-loading="loading">
      <div class="progress-bar-container">
        <div class="progress-stats">已完成: {{ completedQuestions }}/{{ questionDetails.length }}</div>
        <el-progress :percentage="progressPercentage" :stroke-width="18" :format="progressFormat"></el-progress>
      </div>
      
      <div v-for="(question, index) in questionDetails" :key="question.id" class="question-item">
        <div class="question-header">
          <h3 class="question-title">
            <span class="question-number">{{ index + 1 }}. </span>
            <span v-html="question.questionText"></span>
            <span class="question-type">({{ question.type }})</span>
          </h3>
          <div class="question-score">
            <span>得分: </span>
            <template v-if="question.hasExistingScore">
              <span class="locked-score">{{ scores[question.id] }}</span>
              <el-tooltip content="该题已评分，不可修改" placement="top">
                <i class="el-icon-lock locked-icon"></i>
              </el-tooltip>
            </template>
            <template v-else>
              <el-input-number 
                v-model="scores[question.id]" 
                :min="0" 
                :max="question.maxScore || 10"
                size="small"
                @change="checkChanges"></el-input-number>
            </template>
            <span class="max-score"> / {{ question.maxScore || 10 }}分</span>
          </div>
        </div>
        
        <div class="question-content">
          <!-- 如果有图片，显示图片 -->
          <!-- <div v-if="question.imageUrl" class="question-image">
            <img :src="question.imageUrl" alt="题目图片" />
          </div> -->
          
          <!-- 显示正确答案和学生答案 -->
          <div class="answer-section">
            <div class="answer-label">正确答案:</div>
            <div class="answer-content" v-if="question.isCommit === 1 && question.isCorrect === 1 && question.correctAnswer && question.correctAnswer.trim() !== ''" v-html="question.correctAnswer">
            </div>
          </div>
          <div class="answer-section">
            <div class="answer-label">学生答案:</div>
            <div class="answer-content" v-if="question.answer && question.answer.trim() !== ''">
              {{ question.answer }}
            </div>
            <div class="no-answer" v-else>
              <el-tag type="info">未作答</el-tag>
            </div>
          </div>
          
          <!-- 评语输入 -->
          <div class="comment-section">
            <div class="comment-label">教师评语:</div>
            <!-- 如果评语已存在，显示只读评语 -->
            <template v-if="question.hasExistingComment">
              <div class="locked-comment">
                {{ comments[question.id] }}
                <el-tooltip content="该题已有评语，不可修改" placement="top">
                  <i class="el-icon-lock locked-icon"></i>
                </el-tooltip>
              </div>
            </template>
            <!-- 否则显示可编辑的文本框 -->
            <template v-else>
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入评语"
                v-model="comments[question.id]"
                @input="checkChanges"></el-input>
            </template>
          </div>
        </div>
      </div>
      
      <!-- 无题目时显示 -->
      <div v-if="questionDetails.length === 0" class="empty-questions">
        <el-empty description="暂无题目数据"></el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'PublishDetail',
  data() {
    return {
      testId: '',
      studentId: '',
      teacherId: '', 
      loading: true,
      saving: false,
      questionDetails: [
        {
          id:0,
          examId:0,
          questionText:'',
          type:'',
          correctAnswer:'',
          answer:'',
          comment:'',
          score:0,
        }
      ],
      scores: {},
      comments: {},
      testInfo: {
        id:'',
        purpose: '加载中...',
        totalScore: 0,
        endTime: new Date(),
        questionCount: 0
      },
      studentName: '未知',
      studentTotalScore: 0,
      hasChanges: false,
      originalScores: {}
    }
  },
  computed: {
    completedQuestions() {
      return this.questionDetails.filter(q => q.answer && q.answer.trim() !== '').length
    },
    progressPercentage() {
      if (this.questionDetails.length === 0) return 0
      return (this.completedQuestions / this.questionDetails.length) * 100
    },
    isExpired() {
      return new Date() > new Date(this.testInfo.endTime)
    }
  },
  created() {

    console.log('路由参数:', this.$route.params);
    this.questionDetails = this.$route.params.studentResult;
   // this.testId = this.$route.params.id || '';
    // 从查询参数或路由参数获取studentId
    this.studentId = this.$route.query.studentId || this.$route.params.studentId || '';
    
   // console.log('从路由获取 - testId:', this.testId, 'studentId:', this.studentId);
    
    // 2. 如果路由参数中没有，尝试从sessionStorage获取

    console.log('最终获取到 - testId:', this.testId, 'studentId:', this.studentId);
    
    this.getTeacherId();
    
    // 从sessionStorage获取测试信息
    const testInfoStr = sessionStorage.getItem('current_test_info');
    
    if (testInfoStr) {
      try {
        const testInfo = JSON.parse(testInfoStr);
        this.testInfo = {
          ...this.testInfo,
          ...testInfo
        };
        console.log('从sessionStorage获取testInfo:', this.testInfo);
        
        // 如果testInfo中有studentId，且当前没有studentId，使用它
        if (testInfo.studentId && !this.studentId) {
          this.studentId = testInfo.studentId.toString();
          console.log('从testInfo获取studentId:', this.studentId);
        }
        
        // 如果存在预设的分数和评语字段，将其记录下来
        if (testInfo.score !== undefined) {
          this.studentTotalScore = testInfo.score;
        }
      } catch (e) {
        console.error('解析测试信息失败:', e);
      }
    }
    
    // 总是尝试加载数据，如果没有studentId则显示测试概览
    if (!this.studentId) {
      console.log('没有学生ID，显示测试概览信息');
    }
    
    this.loadStudentAnswers()
  },
  methods: {
    // 显示AI助手
    async showAIAssistant() {
      // 显示加载中
      const loadingInstance = this.$loading({
        lock: true,
        text: 'AI 正在分析题目，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      try {
        // 构造问题详情
        const questionData = {
          questions: this.questionDetails.map((q, index) => ({
            index: index + 1, // 添加题目序号
            questionText: q.questionText,
            correctAnswer: q.correctAnswer,
            studentAnswer: q.answer || '未作答',
            score: q.score || '未评分',
            maxScore: q.maxScore || 10
          }))
        };
        
        // 使用 fetch API 发送 POST 请求
        const fetchResponse = await fetch('/ai/ask', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(questionData)
        });
        
        if (!fetchResponse.ok) {
          throw new Error(`HTTP error! status: ${fetchResponse.status}`);
        }
        
        const responseData = await fetchResponse.json();
        // 将响应转换为与之前相同的格式
        const response = {
          data: responseData,
          status: fetchResponse.status,
          statusText: fetchResponse.statusText
        };
        
        if (response.data.success && response.data.data) {
          // 解析AI建议并尝试自动填入分数和评语
          const parsedSuggestions = this.parseAISuggestions(response.data.data);
          
          if (parsedSuggestions.length > 0) {
            // 直接应用AI建议
            const result = this.applyAISuggestions(parsedSuggestions);
            this.$message.success(`AI 已为 ${result.appliedCount} 道题目提供了评分建议并自动填入${result.skippedCount > 0 ? `，跳过 ${result.skippedCount} 个无效建议` : ''}`);
            
            // 显示应用结果
            this.$alert(`
              <div style="max-height: 300px; overflow-y: auto;">
                <h4>AI 评分建议已应用：</h4>
                ${parsedSuggestions.map(suggestion => 
                  `<div style="margin-bottom: 10px; padding: 8px; border: 1px solid #e4e7ed; border-radius: 4px;">
                    <strong>题目${suggestion.questionIndex}:</strong><br>
                    分数: ${suggestion.score}分<br>
                    评语: ${suggestion.comment}
                  </div>`
                ).join('')}
              </div>
            `, 'AI 评分建议', {
              confirmButtonText: '确定',
              customClass: 'ai-message-box',
              dangerouslyUseHTMLString: true
            });
          } else {
            // 没有解析到结构化建议，直接显示原始内容
            this.$alert(response.data.data, 'AI 建议', {
              confirmButtonText: '确定',
              customClass: 'ai-message-box',
              dangerouslyUseHTMLString: true
            });
          }
        } else {
          this.$message.error(response.data.message || '获取AI建议失败');
        }
      } catch (error) {
        console.error('调用AI接口失败:', error);
        this.$message.error('获取AI建议失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        // 关闭加载中
        loadingInstance.close();
      }
    },
    
    // 解析AI建议的结构化数据
    parseAISuggestions(aiResponse) {
      const suggestions = [];
      
      try {
        // 使用正则表达式匹配结构化的建议格式
        // 匹配格式：(1) score：0分 comment：答案错误。题目描述的并发操作中存在数据一致性问题...
        const pattern = /\((\d+)\)\s*score：(\d+)分\s*comment：(.+?)(?=\(\d+\)|$)/gs;
        let match;
        
        while ((match = pattern.exec(aiResponse)) !== null) {
          const questionIndex = parseInt(match[1]);
          const score = parseInt(match[2]);
          const comment = match[3].trim();
          
          suggestions.push({
            questionIndex: questionIndex,
            score: score,
            comment: comment
          });
        }
        
        // 如果没有匹配到，尝试其他可能的格式
        if (suggestions.length === 0) {
          // 尝试匹配更宽松的格式，包括可能的空格和换行
          const fallbackPattern = /\((\d+)\)[^0-9]*(\d+)[^0-9]*comment[：:]\s*(.+?)(?=\(\d+\)|$)/gs;
          while ((match = fallbackPattern.exec(aiResponse)) !== null) {
            const questionIndex = parseInt(match[1]);
            const score = parseInt(match[2]);
            const comment = match[3].trim();
            
            suggestions.push({
              questionIndex: questionIndex,
              score: score,
              comment: comment
            });
          }
        }
        
        // 如果还是没有匹配到，尝试最简单的格式
        if (suggestions.length === 0) {
          const simplePattern = /\((\d+)\).*?(\d+).*?comment[：:]\s*(.+?)(?=\(\d+\)|$)/gs;
          while ((match = simplePattern.exec(aiResponse)) !== null) {
            const questionIndex = parseInt(match[1]);
            const score = parseInt(match[2]);
            const comment = match[3].trim();
            
            suggestions.push({
              questionIndex: questionIndex,
              score: score,
              comment: comment
            });
          }
        }
        
        // 按题目序号排序，确保顺序正确
        suggestions.sort((a, b) => a.questionIndex - b.questionIndex);
        
        console.log('解析到的AI建议:', suggestions);
        console.log('原始AI响应:', aiResponse);
      } catch (error) {
        console.error('解析AI建议失败:', error);
      }
      
      return suggestions;
    },
    
    // 应用AI建议到对应的题目
    applyAISuggestions(suggestions) {
      let appliedCount = 0;
      let skippedCount = 0;
      
      suggestions.forEach(suggestion => {
        // 根据题目序号找到对应的题目
        const questionIndex = suggestion.questionIndex - 1; // 转换为数组索引
        const question = this.questionDetails[questionIndex];
        
        if (question) {
          // 验证分数是否在合理范围内
          const maxScore = question.maxScore || 10;
          const validScore = Math.max(0, Math.min(suggestion.score, maxScore));
          
          // 更新分数和评语
          this.scores[question.id] = validScore;
          this.comments[question.id] = suggestion.comment;
          
          console.log(`应用AI建议到题目${suggestion.questionIndex}:`, {
            questionId: question.id,
            score: validScore,
            comment: suggestion.comment,
            maxScore: maxScore
          });
          
          appliedCount++;
        } else {
          console.warn(`未找到题目${suggestion.questionIndex}，跳过该建议`);
          skippedCount++;
        }
      });
      
      // 标记有更改
      this.hasChanges = true;
      
      console.log(`AI建议应用完成：成功应用${appliedCount}个，跳过${skippedCount}个`);
      
      return { appliedCount, skippedCount };
    },
    async loadStudentAnswers() {
      this.loading = true
      
      try {
    
        // 调用后端接口获取学生测试详情
        // 使用Promise.all等待所有异步操作完成
        await Promise.all(this.questionDetails.map(async detail => {
          const response = await axios.get(`/result/${detail.id}`, { 
            params: { 
              _t: new Date().getTime() // 防缓存
            } 
          })
          console.log('response', response);
          detail.answer = response.data.answer;
          detail.comment = response.data.comment;
          detail.score = response.data.score;
          detail.maxScore = response.data.maxScore;
          detail.isCorrect = response.data.isCorrect;
          detail.isCommit = response.data.isSubmit; // 后端返回的是isSubmit，映射为isCommit
          //获取题目文本和正确答案
          await this.getQuestionDetailsByIds(detail);
        }))

      } catch (error) {
        console.error('获取学生答案数据出错:', error)
      } finally {
        console.log('questionDetails', this.questionDetails);
       
        // 初始化分数和评语对象
        this.questionDetails.forEach(detail => {
          this.scores[detail.id] = detail.score || 0;
          this.comments[detail.id] = detail.comment || '';
        });
        
        // 设置学生姓名
        if (this.questionDetails.length > 0) {
          this.studentName = this.questionDetails[0].studentName || `学生ID: ${this.questionDetails[0].studentId}`;
        }
        
        // 保存原始分数用于比较是否有变化
        this.originalScores = {...this.scores};
        
        this.loading = false
      }

    },
    
    // 新增方法：根据问题ID获取问题详情
    async getQuestionDetailsByIds(detail) {

      const response = await axios.get('/question/query', { 
        params: { 
          id: detail.questionId,
          _t: new Date().getTime() // 防缓存
        } 
      })
        console.log('questionresponse', response.data.data);
      detail.type = response.data.data.type;
      detail.questionText = response.data.data.questionText;
      detail.correctAnswer = response.data.data.Answer;
      return detail;
    },
    
    processQuestionDetails(details) {
    //   this.questionDetails = []
    //   console.log('正在处理问题详情:', details)
    //   if (!Array.isArray(details) || details.length === 0) {
    //     this.loading = false
    //     return
    //   }
      
    //   // 设置学生姓名
    //   if (details[0]) {
    //     this.studentName = details[0].studentName || `学生ID: ${details[0].studentId}`
    //   }
      
    //   // 计算学生获得的总分
    //   let totalScoreEarned = 0
      
    //   // 处理每个问题
    //   details.forEach(item => {
    //     // 根据API返回的数据结构调整字段
    //     const question = {
    //       id: item.id||item.questionId,
    //       examId:item.examId,
    //       questionText: item.questionText || item.text || '未知题目',
    //       type: item.type || '未知类型',
    //       imageUrl: item.imageUrl,
    //       correctAnswer: item.correctAnswer || '',
    //       answer: item.answer || '',
    //       score: item.actualScore || 0, // 学生已获得的分数,使用actualScore字段
    //       maxScore: item.score || 10,   // 题目满分
    //       comment: item.comment || ''   // 使用comment字段作为评语
    //     }
        
    //     // 累加学生已获得的分数
    //     totalScoreEarned += question.score
        
    //     // 添加hasExistingScore标志
    //     question.hasExistingScore = question.score > 0
        
    //     // 添加hasExistingComment标志
    //     question.hasExistingComment = question.comment && question.comment.trim() !== ''
        
    //     this.questionDetails.push(question)
        
    //     // 初始化分数和评语
    //     this.scores[question.id] = question.score
    //     this.comments[question.id] = question.comment
    //   })
      
    //   // 设置学生总分
    //   this.studentTotalScore = totalScoreEarned
      
    //   // 保存原始分数用于比较是否有变化
    //   this.originalScores = {...this.scores}
    //   this.loading = false
    // 
    },
    
    formatDate(dateString) {
      if (!dateString) return '未知'
      
      const date = new Date(dateString)
      
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    
    progressFormat(percentage) {
      return percentage === 100 ? '已完成' : `${percentage.toFixed(0)}%`
    },
    
    checkChanges() {
      // 检查分数或评语是否有变化
      this.hasChanges = false
      
      for (const id in this.scores) {
        if (this.scores[id] !== this.originalScores[id]) {
          this.hasChanges = true
          break
        }
      }
    },
    
    async saveGrades() {
      if (!this.hasChanges) {
        this.$message.info('没有需要保存的更改')
        return
      }
      
      this.saving = true
      // 构建要提交的数据
      console.log('正在保存评分和评语...');
      console.log('thisquestionDetails', this.questionDetails);
      
      // 添加详细的调试信息
      console.log('this.testInfo:', this.testInfo);
      console.log('this.scores:', this.scores);
      console.log('this.comments:', this.comments);
      
      const updateData = this.questionDetails.map(question => {
        console.log('处理题目:', question);
        const data = {
          id: question.id, // 使用 question.id 而不是 question.examId
          questionId: question.questionId, // 使用 questionId 字段
          studentId: this.testInfo.studentId,
          testId: this.testInfo.id,
          actualScore: this.scores[question.id],
          comment: this.comments[question.id] 
        };
        console.log('构建的数据项:', data);
        return data;
      });
      
      console.log('map后的数据:', updateData);
      
      const filteredData = updateData.filter(item => {
        // 找到对应的问题 - 使用 results 表的 id 来匹配
        const question = this.questionDetails.find(q => q.id === item.id);
        console.log('过滤检查 - item:', item, 'question:', question);
        // 只包含可修改的题目
        const shouldInclude = question && !question.hasExistingScore && !question.hasExistingComment;
        console.log('是否包含:', shouldInclude, 'hasExistingScore:', question?.hasExistingScore, 'hasExistingComment:', question?.hasExistingComment);
        return shouldInclude;
      });
      
      console.log('过滤后的数据:', filteredData);
      
      // 如果没有可修改的题目，提示用户并返回
      if (filteredData.length === 0) {
        this.saving = false
        this.$message.info('所有题目都已评分，没有需要更新的数据')
        return
      }
      
      console.log('Saving grades:', filteredData)
      
      // 调用后端API保存评分和评语
      const response = await axios.post('/result/updatescoreandcomment', filteredData);
      
      console.log('API响应:', response);
      
      this.$message.success('评分已保存');
      
      // 重置更改标志
      this.hasChanges = false;
      
      // 更新原始数据，反映当前状态
      for (const questionId in this.scores) {
        this.originalScores[questionId] = this.scores[questionId];
      }
      
      // 设置一个特殊标记，表示已更新数据需要刷新
      sessionStorage.setItem('need_refresh_publish', 'true');
      sessionStorage.setItem('publish_refresh_timestamp', Date.now().toString());
      
      // 询问用户是否返回到测试列表
      await this.$confirm('评分已保存。您想返回到测试列表吗?', '提示', {
        confirmButtonText: '返回测试列表',
        cancelButtonText: '继续评分',
        type: 'info'
      }).then(() => {
        // 用户选择返回
        this.$router.push({ name: 'MyPublish' });
      }).catch(() => {
        // 用户选择留在当前页面，不做任何操作
      });
    },
    
    goBack() {
      if (this.hasChanges) {
        this.$confirm('您有未保存的更改，确定要离开吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 在返回前设置一个标记，通知MyPublish页面需要刷新数据
          sessionStorage.setItem('need_refresh_publish', 'true');
          
          // 确保使用原始的教师ID
          const originalTeacherId = sessionStorage.getItem('original_teacher_id');
          if (originalTeacherId) {
            console.log('使用原始教师ID返回:', originalTeacherId);
            sessionStorage.setItem('teacherId', originalTeacherId);
          } else if (this.teacherId) {
            console.log('使用当前组件的教师ID返回:', this.teacherId);
            sessionStorage.setItem('teacherId', this.teacherId);
          }
          
          this.$router.push({ name: 'MyPublish' });
        }).catch(() => {
          // 用户取消，不做任何操作
        });
      } else {
        // 在返回前设置一个标记，通知MyPublish页面需要刷新数据
        sessionStorage.setItem('need_refresh_publish', 'true');
        
        // 确保使用原始的教师ID
        const originalTeacherId = sessionStorage.getItem('original_teacher_id');
        if (originalTeacherId) {
          console.log('使用原始教师ID返回:', originalTeacherId);
          sessionStorage.setItem('teacherId', originalTeacherId);
        } else if (this.teacherId) {
          console.log('使用当前组件的教师ID返回:', this.teacherId);
          sessionStorage.setItem('teacherId', this.teacherId);
        }
        
        this.$router.push({ name: 'MyPublish' });
      }
    },
    getTeacherId() {
      return new Promise((resolve) => {
        // 首先尝试从sessionStorage获取
        let teacherId = sessionStorage.getItem('teacherId');
        
        // 如果从sessionStorage获取失败，尝试从Vuex获取
        if (!teacherId && this.$store && this.$store.state && this.$store.state.userInfo) {
          teacherId = this.$store.state.userInfo.userId;
        }
        
        // 如果从Vuex获取失败，尝试从localStorage获取
        if (!teacherId && localStorage.getItem('userInfo')) {
          try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            if (userInfo && userInfo.userId) {
              teacherId = userInfo.userId;
            }
          } catch (error) {
            console.error('从localStorage解析用户信息出错:', error);
          }
        }
        
        if (teacherId) {
          console.log('PublishDetail获取到teacherId:', teacherId);
          this.teacherId = teacherId;
          // 保存到sessionStorage以便后续使用
          sessionStorage.setItem('original_teacher_id', teacherId);
          resolve(teacherId);
        } else {
          console.log('1. 开始执行 getTeacherId 方法');
          console.log('2. 尝试从sessionStorage获取teacherId');
          console.log('3. 尝试从Vuex获取teacherId');
          console.log('4. 尝试从localStorage获取teacherId');
          console.warn('无法获取教师ID，可能会影响数据显示');
          resolve(null);
        }
      });
    },
    showExtendTimeDialog() {
      console.log('1. 开始执行 showExtendTimeDialog 方法');
      console.log('2. testInfo 对象:', this.testInfo);
      console.log('3. 延长截止时间的testId:', this.testId);
      const testId = this.testId || sessionStorage.getItem('current_test_id');
      if (!testId) {
        console.error('无法获取测试ID');
        this.$message.error('无法获取测试ID，请刷新页面重试');
        return;
      }
      console.log('6. 显示输入框');
      return new Promise((resolve, reject) => {
        this.$prompt('请输入要延长的分钟数', '延长截止时间', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[1-9]\d*$/,
          inputErrorMessage: '请输入正整数'
        }).then(({ value }) => {
          console.log('7. 用户输入了值:', value);
          const minutes = parseInt(value);
          
          // 获取教师ID
          console.log('8. 开始获取教师ID');
          this.getTeacherId().then(teacherId => {
            console.log('9. 成功获取到教师ID:', teacherId);
            if (!teacherId) {
              console.error('10. 错误：无法获取教师ID');
              this.$message.error('无法获取教师ID');
              reject(new Error('无法获取教师ID'));
              return;
            }
            console.log('延长截止时间的教师ID:', teacherId);
            
            // 调用后端API延长截止时间
            console.log('11. 调用后端API延长截止时间', {
              testId,
              teacherId,
              minutes
            });
            
            axios.post('/question/extendExamTime', {
              testId: testId,
              teacherId: teacherId,
              minutes: minutes
            }).then(response => {
              console.log('12. 收到API响应:', response);
              
              if (response.data) {
                console.log('13. API响应数据:', response.data);
                
                if (response.data.code === 200) {
                  console.log('14. 操作成功');
                  this.$message.success(`截止时间已延长${minutes}分钟`);
                  
                  // 刷新页面数据
                  this.loadStudentAnswers();
                  resolve(response.data);
                } else {
                  const errorMsg = response.data.message || '操作失败';
                  console.error('15. 操作失败:', errorMsg);
                  this.$message.error(errorMsg);
                  reject(new Error(errorMsg));
                }
              } else {
                console.error('16. 无效的响应数据:', response);
                const errorMsg = '无效的响应数据';
                this.$message.error(errorMsg);
                reject(new Error(errorMsg));
              }
            }).catch(error => {
              console.error('17. 调用API时出错:', {
                error: error,
                response: error.response,
                status: error.response?.status,
                data: error.response?.data
              });
              
              let errorMessage = '延长截止时间失败，请稍后再试';
              if (error.response) {
                // 服务器返回了错误响应
                errorMessage = error.response.data?.message || errorMessage;
              } else if (error.request) {
                // 请求已发出但没有收到响应
                errorMessage = '无法连接到服务器，请检查网络连接';
              }
              
              this.$message.error(errorMessage);
              reject(error);
            });
          }).catch(error => {
            console.error('获取教师ID失败:', error);
            reject(error);
          });
        }).catch(error => {
          // 用户取消操作
          if (error !== 'cancel' && error !== 'close') {
            console.error('用户输入错误:', error);
            this.$message.error('操作失败: ' + (error.message || '未知错误'));
          }
          reject(error);
        });
      }).finally(() => {
        console.log('操作完成');
      });
    }
  }
}
</script>

<style scoped>
.ai-assistant-btn {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
  box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.08);
  padding: 4px 12px;
  font-size: 13px;
}

/* AI消息框样式 */
.ai-message-box {
  min-width: 300px;
  max-width: 80%;
}

.publish-detail-container {
  padding: 10px;
  max-width: 1000px;
  margin: 0 auto;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.header-content h2 {
  margin: 0 0 6px 0;
  font-size: 18px;
  color: #303133;
}

.meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  color: #606266;
  font-size: 13px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.meta-item i {
  margin-right: 3px;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 6px;
}

.progress-bar-container {
  margin-bottom: 10px;
  background-color: #f5f7fa;
  padding: 8px 12px;
  border-radius: 3px;
}

.progress-stats {
  margin-bottom: 4px;
  font-size: 12px;
  color: #606266;
}

.question-item {
  margin-bottom: 14px;
  padding: 10px 12px;
  border-radius: 3px;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.06);
  background-color: #fff;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 4px;
  border-bottom: 1px solid #ebeef5;
}

.question-title {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  flex: 1;
}

.question-number {
  color: #409eff;
  font-weight: bold;
  margin-right: 3px;
}

.question-type {
  color: #909399;
  font-size: 12px;
  font-weight: normal;
}

.question-score {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #606266;
}

.max-score {
  margin-left: 3px;
}

.locked-score {
  font-weight: bold;
  color: #606266;
}

.locked-icon {
  margin-left: 3px;
  color: #909399;
}

.question-content {
  padding: 4px 0;
}

.question-image {
  margin-bottom: 8px;
  text-align: center;
}

.question-image img {
  max-width: 100%;
  max-height: 220px;
  border-radius: 3px;
}

.answer-section, .comment-section {
  margin-bottom: 8px;
}

.answer-label, .comment-label {
  font-weight: 500;
  margin-bottom: 3px;
  color: #606266;
  font-size: 13px;
}

.answer-content {
  padding: 6px;
  background-color: #f5f7fa;
  border-radius: 3px;
  white-space: pre-wrap;
  min-height: 32px;
  font-size: 13px;
}

.no-answer {
  text-align: center;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 3px;
  color: #909399;
  font-size: 13px;
}

.locked-comment {
  padding: 6px;
  background-color: #f5f7fa;
  border-radius: 3px;
  color: #606266;
  font-size: 13px;
}

.empty-questions {
  padding: 20px 0;
  text-align: center;
  font-size: 14px;
}

.el-input-number, .el-input__inner, .el-textarea__inner {
  font-size: 13px !important;
  height: 26px !important;
  min-height: 26px !important;
}

.el-button {
  font-size: 13px !important;
  padding: 4px 10px !important;
  height: 28px !important;
}

.el-tag {
  font-size: 12px !important;
  height: 20px !important;
  line-height: 20px !important;
  padding: 0 6px !important;
}

</style>